import {RexProConfigProvider} from "@jeoshi-design/rex-design.other.core";
import {request, useRequest} from "@umijs/max";
import {TemplateTour} from "./components/TemplateTour";
import {Chat, TChatCallbackData} from "./components/Chat";
import * as baseComponents from "./baseComponents";
import {CardInfo, ProForm, ProTable} from "./baseComponents";
import {createElement, useEffect, useRef} from "react";
import {Tools} from "./components/Tools";
import {NodeData} from "@craftjs/core";
import {Modal, Button, message} from "antd";
import {LowCodeEngine, StageActionRef} from "low-code-engine";


const TemplateV2 = () => {
  const actionRef = useRef<StageActionRef>(null);
  const {current: componentIdCache} = useRef<Record<string, string>>({});
  const {run: getDetailApi} = useRequest(
    (id: number, type: 'Template' | 'Kit') => {
      if (type === 'Kit') {
        return request(`/api/kits/${id}`, {method: 'get', });
      }
      return request(`/api/template/${id}`, {method: 'get', });
    },
    {manual: true, },
  );

  const confirm = (data: TChatCallbackData) => {
    if ('id' in data) {
      const modalData = Modal.confirm({
        title: '检测到新内容',
        content: `检测到${data.type === 'Kit' ? '套件' : '模板'}「${data.name}」，请选择操作方式：`,
        footer (originNode, extra) {
          return (
            <div style={{display: 'flex', justifyContent: 'flex-end', width: '100%', gap: 4}}>
              <extra.CancelBtn />
              <Button onClick={async () => {
                try {
                  const res = await getDetailApi(data.id, data.type);
                  const jsonData = JSON.parse(res.content);
                  actionRef.current?.deserialize(jsonData)
                  modalData.destroy();
                } catch (error) {
                  message.error('解析失败或请求失败2');
                }
              }}>覆盖当前内容</Button>
              <extra.OkBtn />
            </div>
          )
        },
        okText: '追加到当前内容',
        onOk: async () => {
          try {
            const res = await getDetailApi(data.id, data.type);
            const jsonData = JSON.parse(res.content);
            actionRef.current?.parseNodeTree(jsonData, (jsonData.ROOT as unknown as NodeData).nodes);
          } catch (error) {
            console.error(error);
            message.error('解析失败或请求失败1');
          }
        }
      });
    }
    else if ('templateType' in data) {
      const {query, actions} = actionRef.current!.getEditor();
      const isRender = componentIdCache[data.componentId] && !!query.node(componentIdCache[data.componentId])?.toSerializedNode();

      Modal.confirm({
        title: '检测到新内容',
        content: `检测到组件「${data.templateType}」，请选择操作方式：`,
        okText: isRender ? '替换' : '追加到当前内容',
        onOk: async () => {
          try {
            const options = query.getOptions();
            const node = query.parseReactElement(createElement(options.resolver[data.templateType], data.params)).toNodeTree();
            if (isRender) {
              actions.setProp(componentIdCache[data.componentId], (props) => {
                Object.keys(data.params).forEach(key => {
                  props[key] = (data.params as any)[key];
                })
              });
            }
            else {
              componentIdCache[data.componentId] = node.rootNodeId;
              actions.addNodeTree(node, 'ROOT');
            }
          } catch (error) {
            console.error(error);
            message.error('解析失败3');
          }
        }
      });
    }
  };

  useEffect(() => {
    const fn = (e: CustomEvent<TChatCallbackData>) => {
      const data = e.detail;
      if (!data) return;
      confirm(data);
    };
    document.addEventListener('SHARE_TEMPLATE_MESSAGE', fn as any);
    return () => {
      document.removeEventListener('SHARE_TEMPLATE_MESSAGE', fn as any);
    }
  }, []);

  return (
    <RexProConfigProvider value={{
      apiClient: async (path, params) => {
        const res = await request('/api/mock' + path, {data: params, method: 'post'});
        return res.data;
      }
    }}>
      <TemplateTour />
      <Chat
        callback={(data) => {
          if (data && ('id' in data || 'templateType' in data)) {
            confirm(data);
          }
        }}
      />
      <div style={{display: 'flex', flexDirection: 'column', height: '100vh'}}>
        <LowCodeEngine
          actionRef={actionRef}
          items={[
            {
              label: 'Pro',
              key: 'pro',
              components: [
                CardInfo,
                ProForm,
                ProTable,
              ],
            }
          ]}
          componentMap={baseComponents}
          headerRender={({preview}) => (
            <div
              style={{
                padding: '8px 16px',
                borderBottom: '1px solid #d3d3d3',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              IAS Editor <Tools preview={preview} actionRef={actionRef} />
            </div>
          )}
        />
      </div>
    </RexProConfigProvider>
  )
};

export default TemplateV2;
